package cn.com.atlasdata.atops.helper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.*;

/**
 * 连接助手类
 *
 * @author ZJH
 * @create 2018-08-27 12:08
 **/
public class ConnectHelper {
    private static final Logger log = LoggerFactory.getLogger(ConnectHelper.class);
    public static Connection getConnection(String host,String port,String dbName,String user,String password,String dbType) {
        String type = "jdbc:postgresql";
        String driver = "org.postgresql.Driver";
        if (AtopsConstants.dbtype_mysql.equalsIgnoreCase(dbType)){
            type = "jdbc:mysql";
            driver = "com.mysql.cj.jdbc.Driver";
        }
        String url =  type + "://" + host + ":" + port + "/" + dbName;
        Connection conn = null ;
        try {
            //从连接池获取连接
            conn = ConnectionPoolManager.getInstance().getConnection(dbName,type,driver,url,user,password );

//               Class.forName(driver);
//                // 防止数据库连接不上时返回jdbcdriver的错误
//                conn = DriverManager.getConnection(url,user,password);
        } catch (Exception e) {
            String msg = "获取数据库连接失败:" + e.getMessage();
            log.error(msg,e);
        } finally {

        }
        return  conn;
    }

    public static String  execSql(Connection conn,String sql){
        String result = "";
        Statement stmt=null;
        ResultSet rs=null;
        try
        {
            stmt=conn.createStatement();
            rs=stmt.executeQuery(sql);
            while(rs.next()){
                System.out.println(rs.getRow());
                result = result + rs.getInt(1) + "\n";
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return  result;
    }
}
